package ch.mobi.osgi2maven2.config;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import ch.mobi.osgi2maven.config.PredefinedDependencies;

public class MappingConfigParser {

	public static PredefinedDependencies getConfig(String file)
			throws FileNotFoundException {
		JAXBContext context;
		Unmarshaller unmarshaller;
		PredefinedDependencies configObject = null;

		try {
			context = JAXBContext.newInstance(PredefinedDependencies.class);

			unmarshaller = context.createUnmarshaller();

			File configFile = new File(file);
			if (configFile.exists()) {
				// System.out.println("unmarshalling: " + configFile);
				configObject = (PredefinedDependencies) unmarshaller
						.unmarshal(configFile);
			} else {
				InputStream fileFromClassLoader = Thread.currentThread()
						.getContextClassLoader().getResourceAsStream(file);
				if (fileFromClassLoader == null) {

					fileFromClassLoader = MappingConfigParser.class
							.getResourceAsStream(file);

					if (fileFromClassLoader == null) {

						throw new FileNotFoundException(file);
					}
				}
				configObject = (PredefinedDependencies) unmarshaller
						.unmarshal(fileFromClassLoader);

			}
		} catch (JAXBException e) {
			throw new RuntimeException(e);
		}

		return configObject;
	}

}
